﻿using BW.Mes.WinForms.Production;
using BW.Mes.WinForms.WareHouse;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using System.Windows.Forms;

namespace BW.Mes.WinForms
{
    public partial class WareHoustForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _wareHouseApiBaseUrl = "https://localhost:7212";
        private List<WareHouseModel> _allWareHouse; // 存储所有数据

        public WareHoustForm()
        {
            InitializeComponent();

            //初始化httpClient
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 窗体加载时获取数据
            this.Load += WareHoustForm_Load;

            // 注册分页控件事件
            userControl12.ClickPageButtonEvent += UserControl1_ClickPageButtonEvent;
            userControl12.ChangedPageSizeEvent += UserControl1_ChangedPageSizeEvent;
            userControl12.JumpPageEvent += UserControl1_JumpPageEvent;


        }

        private async void WareHoustForm_Load(object sender, EventArgs e)
        {
            await LoadWareHouseData();
            DisplayPagedData();
        }

        // 加载仓库数据
        private async Task LoadWareHouseData()
        {
            try
            {
                 _allWareHouse = await GetApiDataAsync<List<WareHouseModel>>("api/WareHouse/GetWareHouse");

                // 设置总记录数和总页数
                userControl12.TotalRows = _allWareHouse.Count;
                userControl12.TotalPages = (int)Math.Ceiling((double)_allWareHouse.Count / userControl12.PageSize);

                // 更新页码信息标签
                userControl12.PageInfo.Text = $"第{userControl12.CurrentPage}/{userControl12.TotalPages}页";


                // 确保清除旧数据源并重新设置
                gridControl1.DataSource = null;
                    gridControl1.DataSource = _allWareHouse;

                    // 确保网格视图显示数据
                    gridView1.PopulateColumns();
                    gridView1.BestFitColumns();
                    gridView1.RefreshData();

                
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
            }
        }

        // 显示分页后的数据
        private void DisplayPagedData()
        {
            if (_allWareHouse == null || _allWareHouse.Count == 0)
                return;

            int startIndex = (userControl12.CurrentPage - 1) * userControl12.PageSize;
            int count = Math.Min(userControl12.PageSize, _allWareHouse.Count - startIndex);

            if (startIndex < 0 || count <= 0)
                return;

            // 获取当前页的数据
            var pagedData = _allWareHouse.Skip(startIndex).Take(count).ToList();

            // 绑定到GridControl
            gridControl1.DataSource = null;
            gridControl1.DataSource = pagedData;

            // 刷新网格视图
            gridView1.BestFitColumns();
            gridView1.RefreshData();
        }

        // 页码按钮点击事件处理
        private void UserControl1_ClickPageButtonEvent(int currentPage)
        {
            DisplayPagedData();
        }

        // 每页显示条数改变事件处理
        private void UserControl1_ChangedPageSizeEvent()
        {
            // 重新计算总页数
            userControl12.TotalPages = (int)Math.Ceiling((double)_allWareHouse.Count / userControl12.PageSize);
            userControl12.PageInfo.Text = $"第{userControl12.CurrentPage}/{userControl12.TotalPages}页";
            DisplayPagedData();
        }

        // 跳转页面事件处理
        private void UserControl1_JumpPageEvent(int jumpPage)
        {
            DisplayPagedData();
        }

        // 获取仓库数据
        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_wareHouseApiBaseUrl}/{endpoint}");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                // 调试显示原始响应内容
                Console.WriteLine($"API响应: {responseBody}");

                // 先解析为JObject以便提取内部数据
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

                // 假设数组数据在"data"字段中
                if (jsonObject["pageDatas"] != null)
                {
                    string dataJson = jsonObject["pageDatas"].ToString();
                    Console.WriteLine($"提取的pageDatas字段: {dataJson}");

                    return JsonConvert.DeserializeObject<T>(dataJson);
                }

                return JsonConvert.DeserializeObject<T>(responseBody);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
                return default;
            }
        }

       

        // 定义数据模型类
        public class WareHouseModel
        {
            public bool IsSelect { get; set; }
            [DisplayName("序号")]
            public long Id { get; set; }
            /// <summary>
            /// 仓库定义编码
            /// </summary>
            [DisplayName("编码")]
            public string WareHouseCoding { get; set; }
            /// <summary>
            /// 仓库定义名称
            /// </summary>
            [DisplayName("名称")]
            public string WareHouseName { get; set; }
            /// <summary>
            /// 仓库定义类型 外键
            /// </summary>
            [DisplayName("仓库定义类型")]
            public long WareHouseStatus { get; set; }
            [DisplayName("仓管员")]
            public long Loginid { get; set; }
            [DisplayName("仓库定义名称")]
            public string loginName { get; set; }
            [DisplayName("地址")]
            public string WareHouseAddress { get; set; }
            [DisplayName("描述")]
            public string WareHouseDescribe { get; set; }

            [DisplayName("创建人")]
            public string CreatedBy { get; set; }
            [DisplayName("创建时间")]
            public DateTime CreatedAt { get; set; }
            [DisplayName("修改时间")]
            public DateTime? UpdatedAt { get; set; }
        }

        




        /// <summary>
        /// 添加仓库按钮的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            CreateWareHouse createWareHouse = new CreateWareHouse();
            createWareHouse.Show();
        }
        // 操作后刷新数据按钮的事件处理
        private void simpleButton4_Click(object sender, EventArgs e)
        {
             LoadWareHouseData();
        }




        /// <summary>
        /// 删除点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void WareHouseDeleteButton3_Click(object sender, EventArgs e)
        {
            var checkedIds = new List<long>();
            for (int rowHandle = 0; rowHandle < gridView1.RowCount; rowHandle++)
            {
                bool isChecked = false;
                var val = gridView1.GetRowCellValue(rowHandle, "IsSelect");
                if (val != null && val is bool)
                    isChecked = (bool)val;
                if (!isChecked) continue;
                var idObj = gridView1.GetRowCellValue(rowHandle, "Id");
                if (idObj == null) continue;
                long id = Convert.ToInt64(idObj);
                checkedIds.Add(id);
            }
            if (checkedIds.Count == 0)
            {
                XtraMessageBox.Show("请先勾选要删除的行！");
                return;
            }
            if (XtraMessageBox.Show($"确认删除选中的 {checkedIds.Count} 条记录？", "批量删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                return;
            using (var client = new HttpClient { BaseAddress = new Uri(_wareHouseApiBaseUrl) })
            {
                foreach (var id in checkedIds)
                {
                    var resp = await client.PutAsync($"/api/WareHouse/DeleteWareHouse?Id={id}",new StringContent("",Encoding.UTF8,"application/json"));
                    if (!resp.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show($"删除 Id={id} 失败：{resp.ReasonPhrase}");
                        return;
                    }
                }
            }
             
            XtraMessageBox.Show("删除完成！");
            // 刷新数据
            await LoadWareHouseData();
            DisplayPagedData();
        }














    }




}